package logic

import (
	"common/comCopier"
	"common/comRsa"
	"common/dao/model"
	"common/utils"
	"context"
	"errors"
	"gorm.io/gorm"

	"gateway/internal/svc"
	"gateway/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpDatauserInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpDatauserInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpDatauserInfoLogic {
	return &UpDatauserInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpDatauserInfoLogic) UpDatauserInfo(req *types.UpUserInfo) (resp *types.Emp, err error) {
	// todo: add your logic here and delete this line
	if req.UUID == "" {
		return nil, errors.New("uuid required")
	}
	var (
		user = model.User{}
	)
	err = comCopier.CopyWithOption(&user, req)
	if err != nil {
		return nil, err
	}
	if user.Password != "" {
		toString, err := utils.Base64ToString(req.Password)
		if err != nil {
			return nil, err
		}
		decrypt, err := comRsa.Decrypt(toString)
		if err != nil {
			return nil, err
		}
		user.Password = decrypt
	}
	db := l.svcCtx.DB
	table := db.Table(model.TableNameUser)
	err = table.Transaction(func(tx *gorm.DB) error {
		if err = tx.Where("uuid = ?", req.UUID).Updates(&user).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return
}
